<template>
  <div id="panel">
    <el-row :gutter="20">
      <!-- 部门数据 -->
      <el-col :span="5" class="head-container">
        <tree-select v-model="deptName" @node-click="handleNodeClick" />
      </el-col>

      <!-- 用户数据 -->
      <el-col :span="19" class="body-container">
        <el-card class="queryForm">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="100px"
          >
            <el-form-item label="时间">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM"
                type="monthrange"
                range-separator="-"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="监测项目" prop="status">
              <el-select
                v-model="jcxm"
                multiple
                collapse-tags
                style="margin-left: 20px"
                placeholder="请选择"
                @change="selectChange"
              >
                <el-option
                  v-for="item in options"
                  :key="item.itemCode"
                  :label="item.itemName"
                  :value="item.itemCode"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="是否达标">
              <el-switch
                v-model="value"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleSwitchChange"
              ></el-switch>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>

          <el-table :data="tableList.rows" border style="width: 100%">
            <el-table-column type="index" label="序号" />
            <el-table-column prop="segmentName" label="点位名称" />
            <el-table-column
              prop="SampleDate"
              sortable
              label="监测时间"
              width="150"
            />
            <el-table-column prop="businessCategory" label="点位类型" />
            <el-table-column
              prop="targetLevelName"
              sortable
              label="水质级别"
              width="100"
            />
            <el-table-column
              prop="TargetLevel"
              sortable
              label="目标级别"
              width="100"
            />
            <el-table-column prop="sfcb" label="是否超标" />

            <!-- <el-table-column prop="cbyz" label="超标因子" /> -->
            <el-table-column
              prop="PollutionItem"
              label="超标描述"
              show-overflow-tooltip
            />
            <el-table-column
              prop="dataSource"
              label="数据来源"
              show-overflow-tooltip
            />
            <el-table-column
              prop="xiuHeWeiValue"
              label="嗅和味监测值"
              width="120"
            />
            <el-table-column prop="seDuValue" label="色度" />
            <!-- 动态渲染监测项目列 -->
            <el-table-column
              v-for="(col, index) in selArr"
              :key="index"
              :prop="col.val"
              :label="col.name"
              sortable
              min-width="165"
            >
              <template slot-scope="scope">
                {{ scope.row[col.val] }}
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import dayjs from "dayjs";
import { getMonitorFactor } from "@/api/dataResources/common";
import { getRiverTree } from "@/api/commonApi";
import {
  getJcDataList,
  getManualWaterDataList,
} from "@/api/dataResources/waterJcData/jcsection";
export default {
  name: "HydrologicStation",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: {
    TreeSelect: () => import("./treeSelect"),
  },
  data() {
    return {
      tableHeight: window.innerHeight - 400,
      value1: [],
      value2: [],
      deptName: undefined,
      deptOptions: undefined,
      options: [],
      jcxm: [],
      factorIdMap: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isoverstandard: undefined,
        isitontimedata: undefined,
        segmentId: undefined,
        compliance: 0, // 初始化时默认传递达标参数（0=达标）
      },
      tableList: { total: 0, rows: [] },
      total: 0,
      dateRange: [],
      ids: [],
      selArr: [],
      value: true, // 开关默认开启（达标）
    };
  },
  created() {
    this.getMonitorFactor();
    this.calcHalfYearTime();
  },
  methods: {
    pageInit() {
      this.getList(); // 初始化时调用接口，此时queryParams已包含compliance=0
    },
    calcHalfYearTime() {
      this.endTime = dayjs().format("YYYY-MM");
      this.startTime = dayjs().subtract(6, "month").format("YYYY-MM");
      this.dateRange = [this.startTime, this.endTime];
    },
    getMonitorFactor() {
      let query = { bussinessCategoryCode: "CBN" };
      getMonitorFactor(query).then((res) => {
        this.options = res.data;
        this.factorIdMap = res.data.reduce((map, factor) => {
          map[factor.itemCode] = factor;
          return map;
        }, {});
        this.jcxm = res.data.map((factor) => factor.itemCode);
        this.selArr = this.selectedItems();
        this.pageInit(); // 监测因子加载完成后初始化数据，确保compliance已设置
      });
    },
    selectChange(value) {
      this.selArr = this.selectedItems();
      this.getList();
    },
    handleNodeClick(data) {
      this.queryParams.segmentId = data;
      this.handleQuery();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    selectedItems() {
      return this.jcxm.map((factorId) => {
        const factor = this.factorIdMap[factorId];
        return factor
          ? {
              name: factor.itemNameUnit,
              val: factorId,
              keepPointBits: factor.keepPointBits || 0,
            }
          : { name: "", val: factorId };
      });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.calcHalfYearTime();
      this.jcxm = [];
      this.selArr = [];
      this.value = true; // 重置为达标状态
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        isoverstandard: undefined,
        isitontimedata: undefined,
        segmentId: undefined,
        compliance: 0, // 重置后仍默认传递达标参数
      };
      this.resetForm("queryForm");
      this.getList();
    },
    handleSwitchChange(checked) {
      // 开关状态与参数绑定（true=达标→0，false=不达标→1）
      this.queryParams.compliance = checked ? 0 : 1;
    },
    handleExport() {},
    getOverDesc(rawRow) {
      const overFactors = [];
      this.jcxm.forEach((factorId) => {
        const isOver = rawRow[`${factorId}_IsOver`];
        const overTimes = rawRow[`${factorId}_OverTimes`];
        const factor = this.factorIdMap[factorId];
        if (isOver === "1" && factor) {
          const desc = overTimes
            ? `${factor.itemName}（超标${overTimes}倍）`
            : `${factor.itemName}（超标）`;
          overFactors.push(desc);
        }
      });
      return overFactors.length > 0 ? overFactors.join("，") : "-";
    },
    getList() {
      let query = JSON.parse(JSON.stringify(this.queryParams));
      // 确保无论何种情况，compliance参数都会被传递（0或1）
      if (this.dateRange.length > 0) {
        query.beginTime = this.dateRange[0];
        query.endTime = this.dateRange[1];
      } else {
        query.beginTime = "";
        query.endTime = "";
      }
      query.itemCode = this.jcxm ? this.jcxm.join(",") : "";
      query.prop = "CBF8";

      // 打印参数确认（调试用，可删除）
      console.log("接口查询参数：", query);

      getManualWaterDataList(query).then((res) => {
        this.tableList.total = res.total || 0;
        const rawDataList = res.data || [];

        this.tableList.rows = rawDataList.map((rawRow) => {
          const handledRow = {
            segmentName: rawRow.segmentName || rawRow.SegmentName || "-",
            SampleDate: rawRow.SampleDate || "-",
            targetLevelName: rawRow.Level || "-",
            TargetLevel: rawRow.TargetLevel || "-",
            sfcb: rawRow.SegmentIsOver || "-",
            businessCategory: rawRow.AssessType || "-",
            cbyz: rawRow.PollutionItem || "-",
            cbms: this.getOverDesc(rawRow),
            PollutionItem: rawRow.PollutionItem || "-",
            dataSource: rawRow.dataSource || "-",
            xiuHeWeiValue: "-",
            seDuValue: "-",
          };

          this.selArr.forEach((col) => {
            const factorId = col.val;
            const val = rawRow[`${factorId}_Val`];

            if (val === -1 || val === null || val === undefined) {
              handledRow[factorId] = "-";
              return;
            }

            const keepBits = Number(col.keepPointBits) || 1;
            handledRow[factorId] = Number(val).toFixed(keepBits);
          });

          return handledRow;
        });

        this.total = res.total || 0;
      });
    },
    formatSampleDate(rawRow) {
      if (rawRow.SampleDate) {
        return dayjs(rawRow.SampleDate).format("YYYY-MM");
      }
      if (rawRow.yeraSampleDate && rawRow.moonSampleDate) {
        return `${rawRow.yeraSampleDate}-${String(
          rawRow.moonSampleDate
        ).padStart(2, "0")}`;
      }
      return "未知时间";
    },
  },
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    .el-form-item {
      margin: 10px 0 10px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
    }

    .searchBtnBox {
      display: inline-block;
      margin: 10px 0 10px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 20px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}
</style>
